import cv2 as cv
from matplotlib import pyplot as plt


def back_projection_demo():
    roi = cv.imread('roi.jpg',1)
    target = cv.imread('messi5.jpg',1)

    hsv_roi = cv.cvtColor(roi, cv.COLOR_BGR2HSV)
    hsv_target = cv.cvtColor(target, cv.COLOR_BGR2HSV)

    hist_roi = cv.calcHist([hsv_roi],[0,1],None,[180,256],[0,180,0,256])
    cv.normalize(hist_roi,hist_roi,0,255,cv.NORM_MINMAX)
    dst = cv.calcBackProject([hsv_target],[0,1],hist_roi,[0,180,0,256],1)
    cv.imshow('back projection demo',dst)
    cv.imshow('origin ',target)
    bn = cv.bitwise_not(dst)
    cv.imshow('bn',bn)


def hist_2d_demo(image):
    hsv = cv.cvtColor(image,cv.COLOR_BGR2HSV)
    hist = cv.calcHist([hsv],[0,1],None,[50,60],[0,180,0,256])
    cv.imshow('hist_2d',hist)
    plt.imshow(hist,interpolation='nearest')
    plt.title('plt')
    plt.show()


src = cv.imread('lena.jpg', 1)
cv.namedWindow('demo', cv.WINDOW_AUTOSIZE)
cv.imshow('demo', src)
# hist_2d_demo(src)
back_projection_demo()
cv.waitKey(0)
cv.destroyWindow('demo')